package com.matriq.cloudmanager.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.matriq.cloudmanager.R;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import net.lgpage.util.Cleaner;

public class DownloadService extends Service {

	public class DownloadBinder extends Binder {

		public DownloadService getService() {
			return DownloadService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return new DownloadBinder();
	}

	public static Intent getDownloadIntent(Context context, final int itemId, String url, String filename) {
		Intent it = new Intent();
		it.setClass(context, DownloadService.class);
		it.putExtra("itemId", itemId);
		it.putExtra("url", url);
		it.putExtra("filename", filename);
		it.putExtra("action", "download");
		return it;
	}
	public static Intent getStopIntent(Context context,  String url) {
		Intent it = new Intent();
		it.setClass(context, DownloadService.class);
		it.putExtra("url", url);
		it.putExtra("action", "stop");
		return it;
	}
	@Override
	public void onCreate() {
		registerReceiver(recevier, NetWorkRecevier.getIntentFilter());
		super.onCreate();
	}
	ExecutorService executorService = Executors.newFixedThreadPool(5);
	boolean isMobileAccess = false;

	NetWorkRecevier recevier = new NetWorkRecevier() {

		@Override
		public void onWifiConnected() {
			startAll();
		}

		@Override
		public void onMobileConnected() {
			if(isMobileAccess){
				startAll();
			}else{
				stopAll();
			}
		}

		@Override
		public void onDisconnected() {
			stopAll();
		}
	};
	
	public void stopAll(){
		Iterator<ServiceDownloadTask> it = taskMap.values().iterator();
		List<ServiceDownloadTask>urls = new ArrayList<>();
		while(it.hasNext()){
			urls.add(it.next());
		}
		for(int i =0;i<urls.size();i++){
			stop(urls.get(i).getUrl());
		}
	}

	public void startAll(){
		Iterator<ServiceDownloadTask> it = stopMap.values().iterator();
		List<ServiceDownloadTask>urls = new ArrayList<>();
		while(it.hasNext()){
			urls.add(it.next());
		}
		for(int i =0;i<urls.size();i++){
			downloadTask(urls.get(i));
		}
	}
	@Override
	public int onStartCommand(Intent it, int flags, int startId) {
		Log.e("haha", "onStartCommand" +it);
		
		if(it!=null&&it.getExtras()!=null){
			Bundle bd = it.getExtras();
			Log.e("haha", "onStartCommand" +bd);
			String action = bd.getString("action");
			String url = bd.getString("url");
			RemoteViews rv = bd.getParcelable("RemoteViews");
			if("download".equals(action)){
				long itemId =bd.getLong("itemId", -1);
				String filename = bd.getString("filename");
				download(itemId, url, filename);
			}else{
				stop(url);
				if(rv!=null){
					rv.setImageViewResource(R.id.ib_play, R.drawable.videoplayer_play_selector);
				}
			}
		}
		return START_REDELIVER_INTENT;
	}

	String dir = Environment.getExternalStorageDirectory().getPath() + "/devicectrl";

	Map<String, ServiceDownloadTask> taskMap = new HashMap<>();
	Map<String, ServiceDownloadTask> stopMap = new HashMap<>();

	public ServiceDownloadTask getDownloadTask(String url){
		ServiceDownloadTask task = taskMap.get(url);
		if(task == null){
			task = stopMap.get(url);
		}
		return task;
	}
	public boolean isDownloading(String url) {
		return taskMap.containsKey(url);
	}
	public boolean isStop(String url) {
		return stopMap.containsKey(url);
	}
	public void stop(String url) {
		ServiceDownloadTask task = taskMap.get(url);
		if (task != null) {
			task.cancel();
			taskMap.remove(url);
			stopMap.put(url, task);
		}
		Log.e("haha", "size:"+taskMap.size()+" - "+stopMap.size());
	}
	
	private void downloadTask(ServiceDownloadTask dt){
		download(dt.getItemId(), dt.getUrl(), dt.getFilename());
	}

	public void download(final long itemId, final String url, String filename) {
		stop(url);
		ServiceDownloadTask task = new ServiceDownloadTask(this, itemId, url, dir, filename);
		taskMap.put(url, task);
		task.executeOnExecutor(executorService);
		stopMap.remove(url);
		Log.e("haha", "size:"+taskMap.size()+" - "+stopMap.size());
	}

	public class ServiceDownloadTask extends DownloadTask {

		public ServiceDownloadTask(Context context, Long itemId, String url, String dir, String filename) {
			super(context, itemId, url, dir, filename);
		}

		@Override
		public void onCancelled() {
			super.onCancelled();
			sendBroadcast(DownloadRecevicer.getCancelIntent(itemId, url));
		}

		@Override
		public void onException(Exception e) {
			// super.onException(e);
			cancel();
			sendBroadcast(DownloadRecevicer.getErrorIntent(getItemId(), getUrl()));
			taskMap.remove(getUrl());
		}

		@Override
		public void onProgressChange(long progress, long maxlength) {
			super.onProgressChange(progress, maxlength);
			//Log.e("haha", url+" - "+progress);
			sendBroadcast(DownloadRecevicer.getProgressChangeIntent(getItemId(), getUrl(), progress, maxlength));
		}

		@Override
		public void onPostExecuteX(File result) {
			sendBroadcast(DownloadRecevicer.getFinishIntent(getItemId(), getUrl(), result.getPath()));
			taskMap.remove(getUrl());
		}
	}

	@Override
	public void onDestroy() {
		DownloadTask[] tasks = new DownloadTask[taskMap.size()];
		Cleaner.cleanTask(taskMap.values().toArray(tasks));
		taskMap.clear();
		super.onDestroy();
	}

}
